package com.luocj.brvah_srl.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.luocj.brvah_srl.R;
import com.luocj.brvah_srl.fragment.FragmentA;
import com.luocj.brvah_srl.fragment.FragmentB;
import com.luocj.brvah_srl.fragment.FragmentC;
import com.luocj.brvah_srl.fragment.FragmentD;


import java.util.ArrayList;

public class TabLayoutActivity extends AppCompatActivity {

    private TabLayout tablayout;
    private ViewPager viewPager;
    private ArrayList<Fragment> fragments;
    private FragmentA afragment;
    private FragmentB bfragment;
    private FragmentC cfragment;
    private FragmentD dfragment;
    private String[] titles = {"A", "B", "C", "D"};
    private String TAG = TabLayoutActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);
        initView();
    }


    private void initView() {
        tablayout = findViewById(R.id.tablyout);
        viewPager = findViewById(R.id.viewpager);
        fragments = new ArrayList<Fragment>();
        afragment = new FragmentA();
        bfragment = new FragmentB();
        cfragment = new FragmentC();
        dfragment = new FragmentD();
        fragments.add(afragment);
        fragments.add(bfragment);
        fragments.add(cfragment);
        fragments.add(dfragment);
        viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        tablayout.setupWithViewPager(viewPager);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.i(TAG, "onPageSelected: " + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private class MyPagerAdapter extends FragmentStatePagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }


}
